/*Copyright (C) 2009 Careil Baptiste

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/

#include <stdio.h>
#include <string.h>
#include "Colors.h"
#include <curses.h>

#define CSLP_BACKGROUND_MASK (0x07 << 3)
#define CSLP_FOREGROUND_MASK 0x07

//fonction interne
///////////////////////////////////////////////////////////
/// Permet de récupérer la pair utilisée
///////////////////////////////////////////////////////////
short CSLP_GetCurrentPair()
{
  short pair;
  attr_t attr;
  attr_get(&attr, &pair, NULL);
  return pair;
}

//fonction externe
///////////////////////////////////////////////////////////
/// Permet de récupérer la couleur de fond
///////////////////////////////////////////////////////////
int DLL_IMPEXP CSLP_GetBackgroundColor()
{
  short pair = CSLP_GetCurrentPair();
  /* text WHITE; bg BLACK */
  if (pair == 0)
  {
    return 0;
  }
  pair--;
  /* text WHITE; bg WHITE */
  if (pair == COLOR_WHITE)
  {
    return COLOR_WHITE;
  }
  return (pair & CSLP_BACKGROUND_MASK) >> 3;
}

//fonction externe
///////////////////////////////////////////////////////////
/// Permet de récupérer la couleur du texte
///////////////////////////////////////////////////////////
int DLL_IMPEXP CSLP_GetForegroundColor()
{
  short pair = CSLP_GetCurrentPair();
  /* text WHITE; bg BLACK*/
  if (pair == 0)
  {
    return COLOR_WHITE;
  }
  return (pair - 1) & CSLP_FOREGROUND_MASK;
}

//fonction externe
///////////////////////////////////////////////////////////
/// Permet l'initialisation de la couleur du fond de la console et du texte
///////////////////////////////////////////////////////////
void DLL_IMPEXP CSLP_Color(int txt, int bg)
{
  attroff(COLOR_PAIR(CSLP_GetCurrentPair()));
  attron(CSLP_GetPairAttr(txt, bg));
}

attr_t DLL_IMPEXP CSLP_GetPairAttr(int txt, int bg)
{
  return (COLOR_PAIR(CSLP_GetPair(txt, bg)));
}

short DLL_IMPEXP CSLP_GetPair(int txt, int bg)
{
  if (txt == COLOR_WHITE && bg == COLOR_BLACK)
  {
    return 0;
  }
  else if (txt == COLOR_WHITE && bg == COLOR_WHITE)
  {
    return COLOR_WHITE + 1;
  }
  return (short)((((txt & CSLP_FOREGROUND_MASK) | ((bg << 3) & CSLP_BACKGROUND_MASK))) + 1);
}
